﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIBag : MonoBehaviour
{
    public BagScrollView bagScrollView;

    private List<ItemData> listItems;

    public Text goldNum;
    public Text propNum;


    private void Awake()
    {
        bagScrollView.onValueChange.AddListener(BagValueChangeHandler);
    }

    private void OnEnable()
    {
        Refesh();
    }

    private void Update()
    {
        if (GameData.isItemChanged)
        {
            Refesh();
            GameData.isItemChanged = false;
        }
    }

    private void BagValueChangeHandler(BagItem bagItem)
    {
        UIBagItemRender itemRender = bagItem.transform.GetComponent<UIBagItemRender>();
        int[] itemRenders = GetItemRenders();
        itemRender.SetData(listItems[itemRenders[bagItem.index]]);
    }

    public void Refesh()
    {
        goldNum.text = GameData.GetPropNum("item10001").ToString();
        propNum.text = GameData.GetPropNum("item30001").ToString();
        listItems = GameData.GetCurRoleItems();
        int itemCount = listItems.Count;
        for (int i = 0; i < listItems.Count; i++)
        {
            ItemInfo itemInfo = listItems[i].GetItemInfo();
            if (itemInfo.type != 2)
            {
                itemCount--;
            }
        }
        bagScrollView.SetCount(itemCount);
    }
    
    public void Close()
    {
        gameObject.SetActive(false);
    }

    private int[] GetItemRenders()
    {
        listItems = GameData.GetCurRoleItems();
        int[] itemRenders = new int[listItems.Count];
        int v = 0;
        for (int i = 0; i < listItems.Count; i++)
        {
            ItemInfo itemInfo = listItems[i].GetItemInfo();
            if (itemInfo.type == 2)
            {
                itemRenders[v] = i;
                v++;    
            }
        }
        return itemRenders; 
    }
}
